//
//  YijingDetailViewController.m
//  TianTianKankan
//
//  Created by sunmingming on 14-8-22.
//  Copyright (c) 2014年 Ebola. All rights reserved.
//

#import "YijingDetailViewController.h"
#import "tooles.h"
#import "AppDelegate.h"
#import <LKDBHelper.h>

@interface YijingDetailViewController ()<AFSoundManagerDelegate>

@property(nonatomic,strong) UIImageView *bgView;

@property(nonatomic,strong) UIButton *lastButton;
@property(nonatomic,strong) UIButton *nextButton;
@property(nonatomic,strong) UILabel *titleLabel;

@property(nonatomic,strong) UITextView *mainTextview;
//44 30 40
@property(nonatomic,strong) UILabel *songBgLabel;
@property(nonatomic,strong) UILabel *songLogoLabel;
@property(nonatomic,strong) UILabel *songTitleLabel;
@property(nonatomic,strong) UIButton *songPlayButton;
@property(nonatomic,strong) UILabel *musicTimeLabel;
@property(nonatomic,strong) UISlider *musicSlider;

@property(nonatomic,assign) BOOL firstPlay;

-(void)playPressed:(id)sender;

-(void)prePressed:(id)sender;
-(void)nextPressed:(id)sender;

@end

@implementation YijingDetailViewController

@synthesize songLogoLabel = _songLogoLabel;
@synthesize songPlayButton = _songPlayButton;
@synthesize songTitleLabel = _songTitleLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [tooles setPlistValue:APPALL.nowLevel ForKey:@"level"];
        APPALL.globalItem = [APPALL.mainBookArray objectAtIndex:(APPALL.nowLevel-1)];
        
        self.bgView = [UIImageView new];
        self.bgView.image = [UIImage imageNamed:@"cover.jpg"];
        [self.view addSubview:self.bgView];
        
        self.titleLabel = [UILabel new];
        self.titleLabel.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
        self.titleLabel.textColor = [UIColor blackColor];
        self.titleLabel.numberOfLines = 0;
        self.titleLabel.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:self.titleLabel];
        
        self.lastButton = [UIButton new];
        [self.lastButton setImage:[UIImage imageNamed:@"abc_ic_ab_back_mtrl_am_alpha.png"] forState:UIControlStateNormal];
        [self.lastButton addTarget:self action:@selector(prePressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.lastButton];
        
        self.nextButton = [UIButton new];
        [self.nextButton setImage:[UIImage imageNamed:@"abc_ic_ab_back_mtrl_am_beta.png"] forState:UIControlStateNormal];
        [self.nextButton addTarget:self action:@selector(nextPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.nextButton];
        
        self.mainTextview = [UITextView new];
        self.mainTextview.backgroundColor = [UIColor colorWithWhite:1 alpha:0.5];
        self.mainTextview.editable = NO;
        self.mainTextview.selectable = NO;
        [self.view addSubview:self.mainTextview];
        
        self.songBgLabel = [UILabel new];
        self.songBgLabel.text = @"";
        self.songBgLabel.backgroundColor = TitleColor;
        [self.view addSubview:self.songBgLabel];
        
        self.songLogoLabel = [UILabel new];
        self.songLogoLabel.text = @"1";
        self.songLogoLabel.numberOfLines = 1;
        self.songLogoLabel.backgroundColor = [UIColor clearColor];
        self.songLogoLabel.textColor = [UIColor blackColor];
        self.songLogoLabel.font = [UIFont fontWithName:@"Arial" size:17.0f];
        self.songLogoLabel.textAlignment = NSTextAlignmentCenter;
        self.songLogoLabel.hidden = NO;
        [self.view addSubview:self.songLogoLabel];
        
        self.songTitleLabel = [UILabel new];
        self.songTitleLabel.text = @"title";
        self.songTitleLabel.numberOfLines = 1;
        self.songTitleLabel.backgroundColor = [UIColor clearColor];
        self.songTitleLabel.textColor = [UIColor whiteColor];
        self.songTitleLabel.font = [UIFont fontWithName:@"Arial" size:17.0f];
        self.songTitleLabel.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:self.songTitleLabel];
        
        self.musicTimeLabel = [UILabel new];
        self.musicTimeLabel.text = @"--:--/--:--";
        self.musicTimeLabel.numberOfLines = 1;
        self.musicTimeLabel.backgroundColor = [UIColor clearColor];
        self.musicTimeLabel.textColor = [UIColor whiteColor];
        self.musicTimeLabel.font = [UIFont fontWithName:@"Arial" size:12.0f];
        self.musicTimeLabel.textAlignment = NSTextAlignmentLeft;
        [self.view addSubview:self.musicTimeLabel];
        
        self.songPlayButton = [[UIButton alloc] init];
        self.songPlayButton.tag = 1;
        [self.songPlayButton setImage:[UIImage imageNamed:@"catalog_group_play_normal.png"] forState:UIControlStateNormal];
        [self.songPlayButton setImage:[UIImage imageNamed:@"catalog_group_pause_normal.png"] forState:UIControlStateSelected];
        [self.songPlayButton addTarget:self action:@selector(playPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:self.songPlayButton];
        
        self.musicSlider = [UISlider new];
        self.musicSlider.enabled = NO;
        self.musicSlider.tintColor = TitleColor;
        self.musicSlider.minimumTrackTintColor = [UIColor blackColor];
        self.musicSlider.maximumTrackTintColor = [UIColor blackColor];
        self.musicSlider.thumbTintColor = [UIColor whiteColor];
        self.musicSlider.value = 0;
        self.musicSlider.minimumValue = 0;
        self.musicSlider.maximumValue = 1;
        [self.view addSubview:self.musicSlider];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    if(APPALL.nowLevel == 0)
        return;
    [self setPage];
}

-(void)setPage{
    APPALL.globalItem = [APPALL.mainBookArray objectAtIndex:(APPALL.nowLevel-1)];
    //    NSLog(@"mainnnn:%@",self.mainItem.Title);
    self.title = APPALL.globalItem.Title;
    // Custom initialization
    self.titleLabel.text = APPALL.globalItem.Original;
    self.mainTextview.text = APPALL.globalItem.Explain;
    self.mainTextview.font = [UIFont fontWithName:@"Arial" size:16.0f];
    [self.mainTextview scrollRectToVisible:CGRectMake(0, 0, 320, 1) animated:NO];
    // Do any additional setup after loading the view from its nib.
    
    self.firstPlay = YES;
    self.musicSlider.value = 0;
    self.musicTimeLabel.text = @"--:--/--:--";
    self.songPlayButton.selected = NO;
    self.songLogoLabel.text = [NSString stringWithFormat:@"%d",APPALL.globalItem.Page];
    self.songTitleLabel.text = APPALL.globalItem.Title;
    [APPALL.globalSoundManager stop];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.mainTextview.font = [UIFont fontWithName:@"Arial" size:16.0f];
    self.firstPlay = YES;
    self.musicSlider.value = 0;
    self.musicTimeLabel.text = @"--:--/--:--";
    self.songPlayButton.selected = NO;
    self.songLogoLabel.text = [NSString stringWithFormat:@"%d",APPALL.globalItem.Page];
    self.titleLabel.text = APPALL.globalItem.Original;
    self.mainTextview.text = APPALL.globalItem.Explain;
    self.songTitleLabel.text = APPALL.globalItem.Title;
    APPALL.globalSoundManager.delegate = self;
    
    WS(ws);
    //TODO use masonry to re-frame all the subviews.
    [self.bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    
    [self.songBgLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ws.view);
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(ws.view);
        make.height.mas_equalTo(60);
    }];
    
    [self.mainTextview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(ws.view);
        make.centerX.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(self.songBgLabel.mas_top);
        make.top.mas_equalTo(ws.view).with.offset(50);
    }];
    
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(ws.view);
        make.right.mas_equalTo(ws.view);
        make.top.mas_equalTo(ws.view);
        make.bottom.mas_equalTo(self.mainTextview.mas_top);
    }];
    
    [self.lastButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
        make.left.mas_equalTo(ws.view).with.offset(8);
        make.top.mas_equalTo(ws.view).with.offset(5);
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(40);
        make.height.mas_equalTo(40);
        make.right.mas_equalTo(ws.view).with.offset(-8);
        make.centerY.mas_equalTo(self.lastButton);
    }];
    
    [self.songLogoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(48, 48));
        make.left.mas_equalTo(ws.view).with.offset(5);
        make.centerY.mas_equalTo(self.songBgLabel);
    }];
    
    [self.songPlayButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(self.songPlayButton.intrinsicContentSize);
        make.right.mas_equalTo(ws.view).with.offset(-5);
        make.centerY.mas_equalTo(self.songBgLabel);
    }];
    
    [self.songTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.songLogoLabel.mas_right).with.offset(5);
        make.right.mas_equalTo(self.songPlayButton.mas_left).with.offset(-5);
        make.bottom.mas_equalTo(self.songBgLabel.mas_centerY);
        make.height.mas_equalTo(20);
    }];
    
    [self.musicTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(80);
        make.right.mas_equalTo(self.songPlayButton.mas_left);
        make.top.mas_equalTo(self.songBgLabel.mas_centerY).with.offset(5);
        make.height.mas_equalTo(20);
    }];
    
    [self.musicSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.songTitleLabel);
        make.right.mas_equalTo(self.musicTimeLabel.mas_left).with.offset(-5);
        make.height.mas_equalTo(30);
        make.centerY.mas_equalTo(self.musicTimeLabel);
    }];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [APPALL.globalSoundManager stop];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)playPressed:(id)sender
{
    UIButton *senderButton = (UIButton*)sender;
    NSLog(@"playPressed :%d",senderButton.tag);
    senderButton.selected = !senderButton.selected;
    if(senderButton.selected)//play
    {
        if(self.firstPlay)
        {
            self.firstPlay = NO;
            [APPALL.globalSoundManager startPlayingLocalFileWithName:[tooles YJMusicNameByIndex:APPALL.globalItem.AudioFilename] withCompletionBlock:^(int percentage, CGFloat elapsedTime, CGFloat timeRemaining, NSError *error, BOOL finished) {
                if (!error) {
                    NSLog(@"yes! %d,%f,%f,%d",percentage,elapsedTime,timeRemaining,finished);
                    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
                    [formatter setDateFormat:@"mm:ss"];
                    
                    NSDate *elapsedTimeDate = [NSDate dateWithTimeIntervalSinceReferenceDate:elapsedTime];
                    
                    NSDate *timeRemainingDate = [NSDate dateWithTimeIntervalSinceReferenceDate:timeRemaining];
                    self.musicTimeLabel.text = [NSString stringWithFormat:@"%@/%@",[formatter stringFromDate:elapsedTimeDate],[formatter stringFromDate:timeRemainingDate]];
                    
                    self.musicSlider.value = percentage * 0.01;
                } else {
                }
            }];
        }
        else
        {
            [APPALL.globalSoundManager resume];
        }
    }
    else
    {
        [APPALL.globalSoundManager pause];
    }
}

-(void)prePressed:(id)sender
{
//    NSLog(@"pre :%d",[sender tag]);
    if(APPALL.nowLevel <= 1)
        return;
    APPALL.nowLevel--;
    [tooles setPlistValue:APPALL.nowLevel ForKey:@"level"];
    APPALL.globalItem = [APPALL.mainBookArray objectAtIndex:(APPALL.nowLevel-1)];
    [self setPage];
}

-(void)nextPressed:(id)sender
{
    NSLog(@"next :%d",[sender tag]);
    if(APPALL.nowLevel >= APPALL.mainBookArray.count)
        return;
    APPALL.nowLevel++;
    [tooles setPlistValue:APPALL.nowLevel ForKey:@"level"];
    APPALL.globalItem = [APPALL.mainBookArray objectAtIndex:(APPALL.nowLevel-1)];
    [self setPage];
}

-(void)currentPlayingStatusChanged:(AFSoundManagerStatus)status
{
//    [self.mainTableView reloadData];
}

@end
